package com.merugu.school.hibernate; /**
 *
 * User: raveendramerugu
 * Date: 1/20/11
 * Time: 6:22 AM
 *
 */

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;

import javax.jws.soap.SOAPBinding;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

public class HibernateSchemaListener implements ServletContextListener {

    private static final String HIBERNATE_SCHEMA_GENERATE = "com.merugu.sms.hibernate.schema.generate";

    // Public constructor is required by servlet spec
    public HibernateSchemaListener() {

    }

    // -------------------------------------------------------
    // ServletContextListener implementation
    // -------------------------------------------------------


    public void contextInitialized(ServletContextEvent sce) {


        Boolean generate = Boolean.valueOf(sce.getServletContext().getInitParameter(HIBERNATE_SCHEMA_GENERATE));

        if (false) {
            try {
                URL url = sce.getServletContext().getResource("/META-INF/hibernate-cfg-xml");
                org.hibernate.cfg.Configuration cfg = new org.hibernate.cfg.Configuration().configure(url);

                new SchemaExport(cfg).create(true, true);
                new SchemaUpdate(cfg).execute(true,false);

                SessionFactory sessionFactory = cfg.buildSessionFactory();
                Session session = sessionFactory.openSession();
                Transaction transaction = session.beginTransaction();
                User user = new User();
                user.setUserName("ravi");
                user.setPassword("ravi");

                UserRole role = new UserRole();
                role.setRole("admin");
                session.save(role);
                session.flush();
                user.setRole(role);
                session.save(user);


                transaction.commit();
                session.close();


            } catch (Exception e) {
             

            }
        }
    }

    public void contextDestroyed(ServletContextEvent sce) {

          sce.getServletContext().getContext("");


    }


}
